import { defineStore } from "pinia"
import { Tag } from "@/models/tag"
import { MaterialPageSearch, MaterialPageResult } from "@/models/material"
import { materialApi, tagApi } from "@/services"
import { toast } from "vue3-toastify"

const useAllMaterialStore  = defineStore('AllMaterial', {
    // state
    state:() =>({
        pageSize: 10,
        pageNum: 1,
        totalRecords: 0,
        materialPageResult: {} as MaterialPageResult,
        tagList: [] as Tag[],
        checkedTagIds: [] as number[],
    }),

    // actions
    actions:{
        // 获取资料Tag列表
        async getMaterialTags() {
            try{
                const res = await tagApi.getMaterialTags()
                this.tagList = res          
            } catch(err) {
                toast.error('获取资料Tag列表出现异常：'+ err);
            }
        },

        // 获取所有的资料列表（分页）
        async getAllMaterials(tagIds:number[], pageSize:number, pageNum:number) {
            try{        
                const data : MaterialPageSearch = {
                    tagList: tagIds,
                    pageSize: pageSize,
                    pageNum: pageNum,
                }
                const res = await materialApi.getAllMaterials(data)
                this.checkedTagIds = tagIds
                this.pageSize = pageSize
                this.pageNum = pageNum
                this.materialPageResult = res
                this.totalRecords = this.materialPageResult.count             
            } catch(err) {
                toast.error('获取所有的资料列表出现异常：'+ err);
            }
        },

        // 加为我的资料
        async addAsMyMaterial(id:number) {
            try {
                const res = await materialApi.addAsMyMaterial(id)
                return res? res.result : false
            } catch(err) {
                return false
            }
        },

        // 初始化数据
        async initData(){
            await this.getMaterialTags();
            await this.refreshData();
        },

        // 刷新数据（在当前页）
        async refreshData(){
            await this.getAllMaterials(this.checkedTagIds,this.pageSize,this.pageNum)
        },

        // 开始查询
        async handleSearch(){      
            await this.getAllMaterials(this.checkedTagIds,this.pageSize,1)
        },

        async handlePageChange(pageNum:number,pageSize:number){     
            this.pageNum = pageNum
            this.pageSize = pageSize   
            this.refreshData()
        }
    },
    getters:{
        materialSource:(state) => state.materialPageResult.records,
        tagSource:(state) => state.tagList,
    }
})

export default useAllMaterialStore;